/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.moxiu.browser;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.moxiu.browser.UrlInputView.StateListener;
import com.moxiu.browser.UrlInputView.UrlInputListener;
import com.moxiu.browser.mainactivity.B_M_bd_BaibuNews;
import com.moxiu.browser.mainactivity.B_M_bd_BaiduSearchHintListParser;
import com.moxiu.browser.util.Common;
import com.moxiu.launcher.R;
import com.moxiu.launcher.config.BDStatistic;
import com.moxiu.launcher.config.StaticConfig;
import com.moxiu.launcher.update.MoxiuPreferenceParam;
import com.moxiu.launcher.widget.baidusb.M_bd_BaiduNewsInfo;
import com.moxiu.market_NetWork.NetWork;
import com.moxiu.market_NetWork.NetWorkCallBack;
import com.moxiu.util.MoxiuParam;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Patterns;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;

public class NavigationBarBase extends LinearLayout implements
        OnClickListener, UrlInputListener, OnFocusChangeListener,
        TextWatcher {

    protected BaseUi mBaseUi;
    protected TitleBar mTitleBar;
    protected UiController mUiController;
    protected Controller controller;
    public UrlInputView mUrlInput;
    
    private int Gray=1;
    private int Black=2;
    private int mTitlebarHight;
    
    public String searchEngine;
    public String searchHintUrl;
    public String searchUrl;
    
    public final String DEFAULT_SEARCH_URL="http://m.baidu.com/s?from=1001706a&word=";
    
    public boolean isSearchbar=false;
    
    public List<M_bd_BaiduNewsInfo> fakeInfo=new ArrayList<M_bd_BaiduNewsInfo>();
    
    public SearchListener mListener;
    
    public void setSearchListener(SearchListener searchListener){
    	mListener=searchListener;
    }
    
    public interface SearchListener{
    	public void searchOnFocus();
    	public void getSearchHint(List<M_bd_BaiduNewsInfo> info);
    	public void searchOnAction(String word);
    	public void clearSearchHint();
    	public void getNoAddrSearchHint(List<M_bd_BaiduNewsInfo> info);
    }
    
    public NavigationBarBase(Context context) {
    
        super(context);

    }

    public NavigationBarBase(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NavigationBarBase(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    	
    }
    /*这个函数是在xml中所有view都加载完了直接执行的*/
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
//        mLockIcon = (ImageView) findViewById(R.id.lock);
//        mFavicon = (ImageView) findViewById(R.id.favicon);
        mUrlInput = (UrlInputView) findViewById(R.id.url);
        
        mUrlInput.setUrlInputListener(this);
        mUrlInput.setOnFocusChangeListener(this);
     //   mUrlInput.setSelectAllOnFocus(true);
        mUrlInput.addTextChangedListener(this);
        mUrlInput.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					if(mListener!=null){
						try {
							if(controller.getCurrentTab().mainManager.isSearchState){
//		        				BDStatistic.postBrowserUrlBarClick(getContext(), ((BrowserActivity)getContext()).mComeFromTag, controller.getCurrentTab().mainManager.searchisFromHome? "1":"0");
		        				return false;
		        			}else{
		        				isSearchbar=false;
		        				controller.getCurrentTab().mainManager.searchisFromHome=controller.getCurrentTab().isShowingHomePage();
		        				BDStatistic.postBrowserUrlBarClick(getContext(), ((BrowserActivity)getContext()).mComeFromTag, controller.getCurrentTab().mainManager.searchisFromHome? "1":"0");
		        			}
		        			try {
		        				
			        			controller.getCurrentTab().showHomePage();
			            		
							} catch (Exception e) {
								e.printStackTrace();
							}
		        			mListener.searchOnFocus();
			        		mUrlInput.requestFocus();
						} catch (Exception e) {
							// TODO: handle exception
						}
	        			
		        	}
				}
				return false;
			}
        	
        });

    }
    

    public void setTitleBar(TitleBar titleBar) {
    	mTitlebarHight = getContext().getResources().getDimensionPixelSize(R.dimen.br_title_bar_height);
        mTitleBar = titleBar;
        mBaseUi = mTitleBar.getUi();
        mUiController = mTitleBar.getUiController();
        mUrlInput.setController(mUiController,mBaseUi,mTitlebarHight);
        controller=(Controller) mUiController;
    }

    public void setLock(Drawable d) {
//        if (mLockIcon == null) return;
//        if (d == null) {
//            mLockIcon.setVisibility(View.GONE);
//        } else {
//            mLockIcon.setImageDrawable(d);
//            mLockIcon.setVisibility(View.VISIBLE);
//        }
    }

    public void setFavicon(Bitmap icon) {
//        if (mFavicon == null) return;
//        mFavicon.setImageDrawable(mBaseUi.getFaviconDrawable(icon));
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        // if losing focus and not in touch mode, leave as is
        if (hasFocus || view.isInTouchMode() || mUrlInput.needsUpdate()) {
            setFocusState(hasFocus);
        }
        if (hasFocus) {
        	mUrlInput.showIME();
            mBaseUi.showTitleBar();
        } else if (!mUrlInput.needsUpdate()) {
            mUrlInput.dismissDropDown();
//            if(!controller.getHomePage().mHBrowserMainManager.isSearchState){
            	mUrlInput.hideIME();
//            }
            if (mUrlInput.getText().length() == 0) {
                Tab currentTab = mUiController.getTabControl().getCurrentTab();
                if (currentTab != null) {
                    setDisplayTitle(currentTab.getUrl());
                }
            }
            mBaseUi.suggestHideTitleBar();
        }
        mUrlInput.clearNeedsUpdate();
    }

    protected void setFocusState(boolean focus) {
    }

    public boolean isEditingUrl() {
        return mUrlInput.hasFocus();
    }

    void stopEditingUrl() {
        WebView currentTopWebView = mUiController.getCurrentTopWebView();
        if (currentTopWebView != null) {
            currentTopWebView.requestFocus();
        }
    }

    void setDisplayTitle(String title) {
        if (!isEditingUrl()) {
            if (!title.equals(mUrlInput.getText().toString())) {
                mUrlInput.setText(title, false);
            }
        }
    }

    void setIncognitoMode(boolean incognito) {
        mUrlInput.setIncognitoMode(incognito);
    }

    void clearCompletions() {
        mUrlInput.dismissDropDown();
    }

 // UrlInputListener implementation

    /**
     * callback from suggestion dropdown
     * user selected a suggestion
     */
    @Override
    public void onAction(String text, String extra, String source) {
    	if(TextUtils.isEmpty(text)){
        	searchWord(text);
        	return;
        }
        stopEditingUrl();
        
        if (UrlInputView.TYPED.equals(source)) {
            String url = UrlUtils.smartUrlFilter(text, false);
            Tab t = mBaseUi.getActiveTab();
            // Only shortcut javascript URIs for now, as there is special
            // logic in UrlHandler for other schemas
            if (url != null && t != null && url.startsWith("javascript:")) {
                mUiController.loadUrl(t, url);
                setDisplayTitle(text);
                
                return;
            }
        }
        if(isSearch(text)){
        	searchWord(text);
        }else{
	        Intent i = new Intent();
	        String action = Intent.ACTION_SEARCH;
	        i.setAction(action);
	        i.putExtra(SearchManager.QUERY, text);
	        if (extra != null) {
	            i.putExtra(SearchManager.EXTRA_DATA_KEY, extra);
	        }
	        if (source != null) {
	            Bundle appData = new Bundle();
	            appData.putString(Common.SOURCE, source);
	            i.putExtra(SearchManager.APP_DATA, appData);
	        }
	        mUiController.handleNewIntent(i);
        }
        setDisplayTitle(text);
    }

    @Override
    public void onDismiss() {
        final Tab currentTab = mBaseUi.getActiveTab();
        mBaseUi.hideTitleBar();
        post(new Runnable() {
            public void run() {
                clearFocus();
                if (currentTab != null) {
                    setDisplayTitle(currentTab.getUrl());
                }
            }
        });
    }

    /**
     * callback from the suggestion dropdown
     * copy text to input field and stay in edit mode
     */
    @Override
    public void onCopySuggestion(String text) {

        mUrlInput.setText(text, true);
        if (text != null) {
        	try {
        		mUrlInput.setSelection(text.length());
			} catch (Exception e) {
				// TODO: handle exception
			}
        }
    }

    public void setCurrentUrlIsBookmark(boolean isBookmark) {
    }

    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent evt) {
    /*	进入多窗口页面处理事件分发机制*/
        if (evt.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            // catch back key in order to do slightly more cleanup than usual
        	mUrlInput.hideIME();
            stopEditingUrl();
//            mUrlInput.clearFocus();
            if (((PhoneUi)mBaseUi).showingNavScreen()) {
            	return false;
            } else {
            	return true;
            }
//        	return false;
        }
        return super.dispatchKeyEventPreIme(evt);
    }
    
    

    @Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
    	if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    		if(mUrlInput.isFocused()){
//    			mUrlInput.clearFocus();
//    			stopEditingUrl();
    			return true;
    		}else{
    			return false;
    		}
    	}
		return super.dispatchKeyEvent(event);
	}

	/**
     * called from the Ui when the user wants to edit
     * @param clearInput clear the input field
     */
    void startEditingUrl(boolean clearInput, boolean forceIME) {
        // editing takes preference of progress
        setVisibility(View.VISIBLE);
        if (mTitleBar.useQuickControls()) {
            mTitleBar.getProgressView().setVisibility(View.GONE);
        }
        if (!mUrlInput.hasFocus()) {
            mUrlInput.requestFocus();
        }
        if (clearInput) {
            mUrlInput.setText("");
        }
        if (forceIME) {
            mUrlInput.showIME();
        }
    }

    public void onProgressStarted() {
    }

    public void onProgressStopped() {
    }

    public boolean isMenuShowing() {
        return false;
    }

    public void onTabDataChanged(Tab tab) {
    	
    }

    public void onVoiceResult(String s) {
        startEditingUrl(true, true);
        onCopySuggestion(s);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    
    boolean isCrasyDog=false;
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
//    	Log.e("DEBUG", " ON TEXT CHANGE-->"+mUrlInput.mState+" LENGTH-->"+s.toString().length());
    	if(controller.getHomePage().mHBrowserMainManager.isSearchState){
	    	if(before!=count&&s.toString().length()>0&&mUrlInput.mState==StateListener.STATE_EDITED
	    			&&!BrowserSettings.getFactoryResetHomeUrl(getContext()).equals(s.toString())
	    			&&!BrowserSettings.getHomePageTitle().equals(s.toString())){
	    		isCrasyDog=false;
	    		mUrlInput.mContainer.setTipSearch();
	    		getHintword(s.toString());
	    	}else if(s.toString().length()==0){
	    		
	    		mUrlInput.mContainer.setTipCancel();
	    		if(mListener!=null){
	    			if(!isCrasyDog){
	    				mListener.clearSearchHint();
	    				isCrasyDog=true;
	    			}
	    		}
	    	}
    	}
    	if(mUrlInput.length()==0){
    		setgray(Gray);
    	}else{
    		setgray(Black);
    	}
    }

    @Override
    public void afterTextChanged(Editable s) { 
    }
    
    public void refreshBit(int state){  }
    public void setgray(int alpha){}
    

    public void onHomePageShowStateChange(boolean show) {
    	
    }    
    public UrlInputView  getAutTextview(){
    	return  mUrlInput;
    }

    
    
    public void switchToNightBase(boolean isNight){
    	//New Code 夜间模式下设置输入框背景颜色及字体颜色
        if (isNight) {
        	 mUrlInput.setBackgroundColor(getResources().getColor(R.color.br_title_night_textbg));
             mUrlInput.setTextColor(getResources().getColor(R.color.br_night_text));
		}else {
			mUrlInput.setBackgroundColor(getResources().getColor(R.color.br_title_day_textbg));
            mUrlInput.setTextColor(getResources().getColor(R.color.moxiu_title_text));
		}
    }
    
    
    /*******************************************************************************************************
     * for search
     * 
     *******************************************************************************************************/
    
    
    private boolean isSearch(String inUrl) {
        String url = UrlUtils.fixUrl(inUrl).trim();
        if (TextUtils.isEmpty(url)) return false;

        if (Patterns.WEB_URL.matcher(url).matches()
                || UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
            return false;
        }
        return true;
    }
    
    private void getHintword(String word){
    	String url="";
    	
    	if(searchEngine==null||searchHintUrl==null||searchEngine.length()<3||searchHintUrl.length()<10){
    		searchEngine = MoxiuPreferenceParam
					.getBackUpSearchFrom(getContext());
    		if(searchEngine!=null||searchEngine.length()>0){
    			if("sogou".equals(searchEngine)){
    				searchHintUrl=MoxiuPreferenceParam.getBackUpSearchTuiBackup(getContext());
    			}else{
    				searchHintUrl = MoxiuPreferenceParam.getBackUpSearchTui(getContext());
    			}
    		}else{
    			searchEngine="baidu";
    		}
    	}else{
	    	if("sogou".equals(searchEngine)||searchEngine.equals("shenma")||searchEngine.equals("littleboy")||searchEngine.equals("fatboy")){
	    		url=searchHintUrl+word;
	    	}else{
	    		url=StaticConfig.MOXIU_M_BD_BAIDU_SEARCH_HINT_URL
						+ word + "&action=opensearch";
	    	}
    	}
    	NetWork netWork = new NetWork();

	    	netWork.getBean(url, new B_M_bd_BaiduSearchHintListParser(),
					new NetWorkCallBack<B_M_bd_BaibuNews>() {
						@Override
						public void onSuccess(B_M_bd_BaibuNews t) {
							super.onSuccess(t);
							if(t!=null&&!t.getNewBaiduHints().isEmpty()){
								if(mListener!=null)
								//mListener.getSearchHint(t.getNewBaiduHints());
								mListener.getNoAddrSearchHint(t.getNewBaiduHints());
							}
						}
	
						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							
						}
					});
    }
    
    public void searchWord(String word){
//    	Log.e("DEBUG", "SEARCH WORD-->"+word);
    	BDStatistic.postBrowserSearch(getContext(), isSearchbar? "101020":"101010", ((BrowserActivity)getContext()).mComeFromTag, word,
    			searchEngine, controller.getCurrentTab().mainManager.searchisFromHome? "1":"0");
    	  
    	if(word!=null&&word.length()>0){
	    	if(mListener!=null){
	    	
	    		mListener.searchOnAction(word);
	    	}
	    	try {
	    		
				word = URLEncoder.encode(word, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				onAction(searchUrl, null, UrlInputView.TYPED);
				return;
			}
	    	
	    	if(searchUrl==null||searchUrl.length()<5){
	    		searchUrl = MoxiuPreferenceParam
						.getBackUpSearchUrl(getContext());
	    	}
	    	if(searchUrl!=null&&searchUrl.length()>5){
	    		onAction(searchUrl+word, null, UrlInputView.TYPED);
	    	}else{

	    		onAction(DEFAULT_SEARCH_URL+word, null, UrlInputView.TYPED);
	    	}
    	}else{
    		if(searchUrl!=null&&searchUrl.length()>5){
    			onAction(searchUrl, null, UrlInputView.TYPED);
    		}else{
//    			controller.handleHomePageIntent(
//    					DEFAULT_SEARCH_URL,
//    					getContext().getPackageName());
    			onAction(DEFAULT_SEARCH_URL, null, UrlInputView.TYPED);
    		}
    	}    	
    }

	@Override
	public void onStor_his(String word) {
		if(word!=null&&word.length()>0){
	    	if(mListener!=null){
	    		mListener.searchOnAction(word);
	    	   }
	    	}	
	}
    
}
